package com.school.controller;

import com.school.common.PageRequest;
import com.school.common.PageResult;
import com.school.common.Result;
import com.school.entity.Class;
import com.school.service.ClassService;
import com.school.utils.ExcelUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;

/**
 * 班级控制器
 */
@Slf4j
@RestController
@RequestMapping("/class")
public class ClassController {
    
    @Autowired
    private ClassService classService;
    
    /**
     * 添加班级
     */
    @PostMapping("/add")
    public Result<Long> add(@Validated @RequestBody Class clazz) {
        Long id = classService.add(clazz);
        return Result.success("添加成功", id);
    }
    
    /**
     * 更新班级
     */
    @PostMapping("/update")
    public Result<Void> update(@Validated @RequestBody Class clazz) {
        classService.update(clazz);
        return Result.success("更新成功");
    }
    
    /**
     * 删除班级
     */
    @DeleteMapping("/delete/{id}")
    public Result<Void> delete(@PathVariable Long id) {
        classService.delete(id);
        return Result.success("删除成功");
    }
    
    /**
     * 批量删除班级
     */
    @PostMapping("/batch-delete")
    public Result<Map<String, Object>> batchDelete(@RequestBody List<Long> ids) {
        try {
            if (ids == null || ids.isEmpty()) {
                return Result.error("请选择要删除的班级");
            }
            log.info("批量删除班级，数量: {}", ids.size());
            int count = classService.batchDelete(ids);
            Map<String, Object> result = new HashMap<>();
            result.put("count", count);
            return Result.success("批量删除成功，共删除 " + count + " 条数据", result);
        } catch (Exception e) {
            log.error("批量删除班级失败", e);
            return Result.error("批量删除失败：" + e.getMessage());
        }
    }
    
    /**
     * 根据ID查询班级
     */
    @GetMapping("/get/{id}")
    public Result<Class> getById(@PathVariable Long id) {
        Class clazz = classService.getById(id);
        return Result.success(clazz);
    }
    
    /**
     * 查询所有班级
     */
    @GetMapping("/all")
    public Result<List<Class>> getAllClasses() {
        List<Class> classes = classService.getAllClasses();
        return Result.success(classes);
    }
    
    /**
     * 分页查询班级列表
     */
    @GetMapping("/list")
    public Result<PageResult<Class>> getList(
            @RequestParam(required = false) String className,
            @RequestParam(required = false) String major,
            @RequestParam(required = false) String status,
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize) {
        
        PageRequest pageRequest = new PageRequest();
        pageRequest.setPageNum(pageNum);
        pageRequest.setPageSize(pageSize);
        
        PageResult<Class> pageResult = classService.getPageList(className, major, status, pageRequest);
        return Result.success(pageResult);
    }
    
    /**
     * 导入班级数据
     */
    @PostMapping("/import")
    public Result<String> importData(@RequestParam("file") MultipartFile file) {
        try {
            List<Map<String, String>> dataList = ExcelUtils.importExcel(file.getInputStream());
            List<Class> classes = new ArrayList<>();
            
            for (Map<String, String> data : dataList) {
                Class clazz = new Class();
                clazz.setClassName(data.get("班级名称"));
                clazz.setTeacherName(data.get("班主任名称"));
                clazz.setPhone(data.get("联系电话"));
                clazz.setMajor(data.get("班级专业"));
                
                String studentCountStr = data.get("学生人数");
                if (studentCountStr != null && !studentCountStr.isEmpty()) {
                    clazz.setStudentCount(Integer.parseInt(studentCountStr));
                } else {
                    clazz.setStudentCount(0);
                }
                
                String status = data.get("状态");
                clazz.setStatus(status != null && !status.isEmpty() ? status : "正常");
                clazz.setRemark(data.get("备注"));
                
                classes.add(clazz);
            }
            
            int count = classService.batchImport(classes);
            return Result.success("导入成功，共导入 " + count + " 条数据");
        } catch (Exception e) {
            log.error("导入班级数据失败", e);
            return Result.error("导入失败：" + e.getMessage());
        }
    }
    
    /**
     * 导出班级数据
     */
    @GetMapping("/export")
    public void exportData(HttpServletResponse response) {
        try {
            List<Class> classes = classService.getAllClasses();
            
            List<String> headers = Arrays.asList(
                    "班级名称", "班主任名称", "联系电话", "班级专业", "学生人数", "状态", "备注"
            );
            
            List<List<Object>> dataList = new ArrayList<>();
            for (Class clazz : classes) {
                List<Object> row = Arrays.asList(
                        clazz.getClassName(),
                        clazz.getTeacherName(),
                        clazz.getPhone(),
                        clazz.getMajor(),
                        clazz.getStudentCount(),
                        clazz.getStatus(),
                        clazz.getRemark()
                );
                dataList.add(row);
            }
            
            String fileName = "班级列表_" + System.currentTimeMillis();
            ExcelUtils.exportExcel(response, fileName, "班级信息", headers, dataList);
        } catch (IOException e) {
            log.error("导出班级数据失败", e);
        }
    }
    
    /**
     * 下载导入模板
     */
    @GetMapping("/template")
    public void downloadTemplate(HttpServletResponse response) {
        try {
            List<String> headers = Arrays.asList(
                    "班级名称", "班主任名称", "联系电话", "班级专业", "学生人数", "状态", "备注"
            );
            
            List<List<Object>> dataList = new ArrayList<>();
            dataList.add(Arrays.asList(
                    "计科2023-1班", "张明", "13800138001", "计算机科学与技术", 45, "正常", ""
            ));
            
            String fileName = "班级导入模板";
            ExcelUtils.exportExcel(response, fileName, "班级信息", headers, dataList);
        } catch (IOException e) {
            log.error("下载模板失败", e);
        }
    }
}

